#include "socket.h"

int sock_create(char *domain, int port, int v) {

   SOCK *sock;
   int conn;

   sock = (SOCK *) malloc(sizeof(SOCK));

   sock->fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
   if( sock->fd == -1)
      return -1;

   sock->s.sin_family = AF_INET;
   sock->s.sin_port = htons(port);

   if(v==VERBOSE) printf("Getting host by name... ");
   fflush(stdout);

   sock->serv = gethostbyname(domain);
   if(sock->serv == NULL) {
      if(v==VERBOSE) printf("can't do the job\n");
      return -1;
   }

   if(v==VERBOSE) printf("Well done.\nConnecting to %s:%d... ", domain, port);
   fflush(stdout);

   sock->s.sin_addr.s_addr = ((struct in_addr *) sock->serv->h_addr)->s_addr;
   conn = connect(sock->fd, (struct sockaddr *)&sock->s, sizeof(sock->s));
   if( conn == -1) { 
      if(v==VERBOSE) printf("fail!\n");
      return -1;
   }

  if(v==VERBOSE) printf("connected!\n");

/*   sock->f = fdopen(sock->fd, "r");
   if( sock->f == NULL )
      return NULL;*/

   return sock->fd;

}

void sock_send(int fd, char *message, ...) {

   char buffer[512];
   va_list l;

   va_start(l, message);
   vsprintf(buffer, message, l);
   va_end(l);

   send(fd, buffer, strlen(buffer), 0);

   return;

}

int download(URI *uri) {

   FILE *fp;
   pthread_t th_downspeed;
   char buffer[512];
   int percent,finish=0;

   fp = fopen("baixando", "w");
   if(fp == NULL) return -1;

   pthread_create(&th_downspeed, NULL, update_progress, (void *)uri);

   uri->sockfd = sock_create(uri->host, uri->port, 2);
   if(uri->sockfd == -1) return -1;
   uri->fp = fdopen(uri->sockfd, "r");

   sock_send(uri->sockfd, "GET / HTTP/1.1\r\n");
   sock_send(uri->sockfd, "Host: %s\r\n\r\n", uri->host);

   while(fgets(buffer, 1024, uri->fp) != NULL && strcmp(buffer,"\r\n") != 0);
   fgets(buffer, 1024, uri->fp);


   while( (finish = recv(uri->sockfd, buffer, 5, 0)) > 0) {

//      finish = fread(buffer, 2, 1, uri->fp);
 //     fwrite(buffer, 2, 1, fp);
int i;
for (i=0;i<5;i++) {
if(buffer[i]=='\n') buffer[i]='|';
if(buffer[i]=='\r') buffer[i]='%';
}
printf("\n---- %s ---- %d\n", buffer, finish);

      /*if(uri->bytes % percent == 0) */show_progress(uri);

      uri->bytes++;

   }


/*   while(feof(uri->fp) == 0 && strcmp(buffer, "\r\n") != 0) {
      finish = fread(buffer, 2, 1, uri->fp);
      fwrite(buffer, 2, 1, fp);

      if(uri->bytes % percent == 0) show_progress(uri);

      uri->bytes++;

   }*/

   fclose(fp);
   fclose(uri->fp);
   close(uri->sockfd);printf("\nsaindo..\n");
   return 1;

}
